<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>md5校验界面</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/spark-md5/3.0.2/spark-md5.min.js"></script>
    <style type="text/css">
        .card-layout {
            margin: 20px;
            padding: 10px;
            display: flex;
            flex-direction: column;
            background: lightgray;
            border-radius: 10px;
        }

        .card-layout > * {
            margin-bottom: 10px;
        }

        .img-view {
            width: 30%;
            height: 150px;
            object-fit: contain;
            word-break: break-all;
        }

        .bottom-layout {
            width: 100%;
            margin-top: 30px;
            text-align: center;
        }
    </style>
</head>
<body>
<h2>前端使用js下载阿里云图片并对比md5值</h2>
<div class="card-layout">
    <p>从接口返回的数据：</p>
    <pre>
{
    status:[[${status}]],
    message:[[${message}]],
    md5:[[${md5}]],
    path:[[${filePath}]]
}
    </pre>
</div>
<div class="card-layout">
    <div>阿里云图片信息：
        <span id="ali-path" style="font-size: smaller;display: none" th:text="${filePath}">这是的内容将被替换</span>
        <span id="ali-upload-md5" style="font-size: smaller;display: none" th:text="${md5}">这是的内容将被替换</span>
    </div>
    <img class="img-view" th:src="${filePath}" th:alt="${filePath}">
    <div>
        <button onClick="downloadBolbToMd5()" style="padding: 5px 10px">获取图片md5值</button>
    </div>
</div>
<div class="card-layout">
    <h4>计算结果：</h4>
    <div>计算图片的md5值：<span id="ali-img-md5" style="color: orangered"></span></div>
    <div>对比结果：<span id="compare-result" style="color: orangered"></span></div>
</div>
<div class="bottom-layout">
    <button onClick="backClick()" style="padding: 5px 20px;">返回上传页面</button>
</div>
<script type="text/javascript">
async function getBlob() {
  let url = document.getElementById('ali-path').innerText
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = () => {
      if (xhr.status === 200) {
        return resolve(xhr.response);
      }
      resolve({})
    };
    xhr.send();
  });
}

async function downloadBolbToMd5() {
  let res = await getBlob()
  console.log("downloadBolbToMd5", res)
  let fileReader = new FileReader()
  let Spark = new SparkMD5.ArrayBuffer()
  fileReader.readAsArrayBuffer(res)
  fileReader.onload = (e) => {
    Spark.append(e.target.result)
    let local_download_md5 = Spark.end()
    let upload_md5 = document.getElementById('ali-upload-md5').innerText
    let compare_result = upload_md5.toLowerCase() == local_download_md5
    console.log("local_download_md5====", local_download_md5)
    document.getElementById('ali-img-md5').innerText = local_download_md5
    document.getElementById('compare-result').innerText = compare_result.toString()
  }
}

function backClick() {
  window.location.href = document.referrer;
}
</script>
</body>
</html>
